package com.bj58.data.emailreports.utils;

import java.io.StringWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocityTools {
	public static HashSet<String> emptyStrSet = new HashSet<String>();
	static{
		emptyStrSet.add(null);
		emptyStrSet.add("");
		emptyStrSet.add("--");
	}
	
	/** Velocity渲染
	 * @param content
	 * @param conMap
	 * @return
	 * @throws Exception
	 */
	public static String render(String content,Map<String,Object> conMap)throws Exception{
		VelocityContext context = new VelocityContext();
		Object tools = TemplateMethodFactory.getInstance(VelocityTools.class);
		context.put("tools",tools);
		
		for(Iterator<String> it  = conMap.keySet().iterator(); it.hasNext();){
			String key = it.next();
			context.put(key,conMap.get(key));
		}
		
		VelocityEngine velocity  = new VelocityEngine();
		Velocity.setProperty("input.encoding", "utf-8");
		Velocity.setProperty("output.encoding", "utf-8");
		
		StringWriter out = new StringWriter();
		try {
				velocity.evaluate(context, out, "", content);
		} catch (Exception e) {            
			e.printStackTrace();
		}
		content = out.toString();
		out.close();
		return content;
	}
	
	public int praseInt(Object o) {
		if (null == o) {
			return 0;
		}
		if (o instanceof Double) {
			return new Double((Double) o).intValue();
		}
		try {
			return new Integer(o.toString()).intValue();
		} catch (Exception e) {
			return 0;
		}
	}
	
	/** 转换时间为字符串格式 yyyy-MM-dd HH:mm*/
	public static String getSimpleTimeStringFromDate(Date date) {
		String pattern = "yyyy-MM-dd HH:mm";
		SimpleDateFormat f = new SimpleDateFormat(pattern);

		return f.format(date);
	}

	
	/** 转换时间为字符串格式 yyyy-MM-dd*/
	public static String getSimpleDateStringFromDate(Date date) {
		if(date == null || "".equals(date)){
			return "";
		}
		String pattern = "yyyy-MM-dd";
		SimpleDateFormat f = new SimpleDateFormat(pattern);

		return f.format(date);
	}
	
	/** 转换时间为字符串格式 yyyy-MM-dd*/
	public static String getSimpleDateStringFromTimestamp(Timestamp tsp) {
		Date date = new Date(tsp.getTime());

		return getSimpleDateStringFromDate(date);
	}
	
	/** 转换时间为字符串格式 yyyy-MM-dd HH:mm*/
	public static String getSimpleTimeStringFromTimestamp(Timestamp tsp) {
		Date date = new Date(tsp.getTime());

		return getSimpleTimeStringFromDate(date);
	}
	
	/** 转换时间为字符串格式 yyyy-MM-dd HH:mm:ss */
	public static String getDateStringFromDate(Date date) {
		String pattern = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat f = new SimpleDateFormat(pattern);

		return f.format(date);
	}

	
	public static String formatDate(Date date,String formatString){
		if(date== null || formatString == null) return "";
		SimpleDateFormat format = new SimpleDateFormat(formatString);
		return format.format(date);
		
	}
	
	public String formatHtml(String productName){
		  String reg="<[^>]+>"; 
		  Pattern p_html=Pattern.compile(reg,Pattern.CASE_INSENSITIVE); 
	      Matcher m_html=p_html.matcher(productName); 
	      productName=m_html.replaceAll(""); 
	      return productName;
	}
	
	public boolean check(Date firstlogintime){
		if(null!=firstlogintime){
			try{
			
				Date nowdatetime = new Date();
				long diff = nowdatetime.getTime()-firstlogintime.getTime();
				if((diff / 86400000) >= 1){
					return false;
				}else {
					return true;
				}
			}catch(Exception e){
				return false;
			}
		}else {
			return true;
		}
	}
	public static String formatNum(double d){
		return formatNum(Double.toString(d));
	}
	public static String formatNum(String s){
		if(s == null) return "0";
		if(s.endsWith(".0") ){
			String num = s.replace(".0", "");
			return num;
		}else{
			try{float f = Float.parseFloat(s);
			int b = (int)Math.round(f * 100);
			float c = b / 100.0f; 
			return Float.toString(c);
			}catch(Exception e){
				return "0";
			}
		}
		
	}
	
	
	public boolean getNewGroup(Date startTime){
		if(startTime == null) return false;
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		//String timeStr = format.format(startTime);
		Date date = new Date(startTime.getTime() + 24*60*60 * 1000);
		return (new Date().compareTo(date) <= 0);
	}
	
	
	/**
	 * 两个时间之间的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException 
	 */
	public static long getDays(Date date1, Date date2) {
		if (date1 == null || date1.equals(""))
			return 0;
		if (date2 == null || date2.equals(""))
			return 0;
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
		long day=0;
		 try {
			day = (myFormatter.parse(myFormatter.format(date1)).getTime() -myFormatter.parse(myFormatter.format(date2)).getTime())/ (24 * 60 * 60 * 1000);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return day;
	}
	
	/**
	 * 获取当前时间
	 * @return
	 */
	public static String getNowDate(){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		return sf.format(date);
	}
	
	/**一键退款支付时间判断，只有当支付时间在2011-6-16 0点之后，才可以显示退款选项 
	 * @param date    订单的支付时间
	 * @return
	 * @throws ParseException 
	 */
	public boolean checkPaydate(Date date) throws ParseException{
		boolean flag= false;
			if(null!=date){
				String reDate="2011-06-16 00:00:00";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date refundDate=sdf.parse(reDate);
				if(refundDate.before(date) || refundDate.equals(date)){
					flag=true;
				}
			}
		return flag;
	}
	
	public 	String mobileHide(String mobile){
		if(null!=mobile && !"".equals(mobile)){
			mobile=mobile.replaceAll(mobile.substring(3, 7), "****");
		}
		return mobile;
	}
	
	public String userNameHide(String userName){
		if(null!=userName && !"".equals(userName)){
			int index =userName.length()/2;
			userName=userName.replaceAll(userName.substring(index, index+2), "***");
		}
		return userName;
	}
	
	
	
	/**计算百分比
	 */
	public  String getRate(int num1, int num2){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num2 == 0){
			return "0.00";
		}
		double rate = (double)num1/num2;
		return df.format(rate*100);
	}
	
	/**流量价值
	 * @return
	 */
	public String getLiuValue(double num1, int num2){
		DecimalFormat df = new DecimalFormat("0.000000");
		if(num2 == 0){
			return "0.00";
		}
		double rate = (double)num1/num2;
		return df.format(rate);
	}
	
	/**百分比转换
	 */
	public  double tranRate(double num){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num == 0){
			return 0;
		}
		return Double.valueOf(df.format(num*100));
	}
	
	
	
	/**将DOUBLE保留0位小数 并转为千分位显示
	 * @param num
	 * @return
	 */
	public  String douDF(Object num){
		if(num==null)
			return "0";
		DecimalFormat df = new DecimalFormat("0");
		DecimalFormat df3 = new DecimalFormat("#,###.###");
		return df3.format(Double.valueOf(df.format(num)));
	}
	
	
	public String qfw(Object a){
		if(null == a){
			return "--";
		}
		DecimalFormat df3 = new DecimalFormat("#,###.###");
		return df3.format(a);
	}
	
	public String qfw2(Object a){
		if(null == a){
			return "--";
		}
		DecimalFormat df3 = new DecimalFormat("#,###,###");
		return df3.format(Double.valueOf(a.toString()));
	}
	
	
	public String judgeShow(String value,String list){
		if(null == list || "".equals(list)){
			return "false";
		}
		String[] temp = list.split(",");
		List<String> values = new ArrayList<String>();
		for(String s : temp){
			values.add(s);
		}
		
		if(values.contains(value) || values.contains("all")){
			return "true";
		}
		return "false";
	}
	
	public String compRate(Object num1,Object num2){
		if(num1==null && num2==null)
    		return "<font color=\"#000000\">0";
    	else if(num1==null)
    		return  "<font color=\"#0000FF\">-100";
    	else if(num2==null)
    		return  "<font color=\"#FF0000\">100";
		DecimalFormat df = new DecimalFormat("0.00");
		DecimalFormat df2 = new DecimalFormat("0.00000");
		
		double num_one = Double.valueOf(df2.format(num1));
		double num_two = Double.valueOf(df2.format(num2));
		
		if(num_one==0 && num_two == 0){
			return  "<font color=\"#000000\">0";
		}else if(num_two == 0){
			return  "<font color=\"#FF0000\">100";
		}else if(num_one == 0){
			return  "<font color=\"#0000FF\">-100";
		}
		
		double sss = (num_one-num_two)/num_two;
		if(sss>0){
			return "<font color=\"#FF0000\">"+df.format(sss*100);
		}else if(sss <0){
			return "<font color=\"#0000FF\">"+df.format(sss*100);
		}else{
			return "<font color=\"#000000\">"+df.format(sss*100);
		}
		
	}
	
	
	
	public String compRate2(Object num1,Object num2){
		if(num1==null && num2==null)
    		return "<font color=\"#000000\">0%</font>";
    	else if(num1==null)
    		return  "<font color=\"#0000FF\">-100%</font>";
    	else if(num2==null)
    		return  "<font color=\"#FF0000\">100%</font>";
		
		DecimalFormat df = new DecimalFormat("0.00");
		DecimalFormat df2 = new DecimalFormat("0.00000");
		
		double num_one = Double.valueOf(df2.format(Double.parseDouble(num1.toString().replace(",", "").replace("%", ""))));
		double num_two = Double.valueOf(df2.format(Double.parseDouble(num2.toString().replace(",", "").replace("%", ""))));
		
		if(num_one==0 && num_two == 0){
			return  "<font color=\"#000000\">0%</font>";
		}else if(num_two == 0){
			return  "<font color=\"#FF0000\">100%</font>";
		}else if(num_one == 0){
			return  "<font color=\"#0000FF\">-100%</font>";
		}
		
		double sss = (num_one-num_two)/num_two;
		if(sss>0){
			return "<font color=\"#FF0000\">"+df.format(sss*100)+"%</font>";
		}else if(sss <0){
			return "<font color=\"#0000FF\">"+df.format(sss*100)+"%</font>";
		}else{
			return "<font color=\"#000000\">"+df.format(sss*100)+"%</font>";
		}
		
	}
	
	
	public String  omitString (String name){
		if(name.length() > 50){
			name = name.substring(0,50)+"......";
		}
		return name;
	}
	
	
	public  String tranRateTwo(double num){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num == 0){
			return "--";
		}
		return String.valueOf(Double.valueOf(df.format(num*100)))+"%";
	}
	
	public  String tranRateThree(double num){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num == 0){
			return "--";
		}
		return String.valueOf(Double.valueOf(df.format(num*100)));
	}
	
	
	public  String xsd(double num){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num == 0){
			return "--";
		}
		return String.valueOf(Double.valueOf(df.format(num)));
	}
	
	
	public  String xsd2(double num){
		DecimalFormat df = new DecimalFormat("0.00");
		if(num == 0){
			return "0";
		}
		return String.valueOf(Double.valueOf(df.format(num)));
	}
	
	
	public  String checkZero(Object a){
		DecimalFormat df3 = new DecimalFormat("0");
		if(df3.format(a).equals("0")){
			return "--";
		}
		return df3.format(a);
	}
	
	
	public  String checkZero2(Object a){
		DecimalFormat df3 = new DecimalFormat("0.0");
		if(df3.format(a).equals("0.0")){
			return "--";
		}
		return df3.format(a);
	}
	
	public String FontColor(Object num1){
		DecimalFormat df = new DecimalFormat("0.00");
		double num_one = Double.valueOf(df.format(num1));
		if(num_one>0){
			return "<font color=\"#FF0000\">"+df.format(num_one);
		}else if(num_one <0){
			return "<font color=\"#0000FF\">"+df.format(num_one);
		}else{
			return "<font color=\"#000000\">"+df.format(num_one);
		}
		
	}
	
	
	
	public String UpperFirst(String abc){
		
		return  abc.substring(0,1).toUpperCase()+ abc.substring(1);
		
	}
	
	
	public <T>Object getValues(String zdName,T vo,Class<T> clazz) throws Exception{
		Method[] mm = clazz.getMethods();
		Map<String,Method> methodMap = new HashMap<String,Method>();
		for(Method m: mm){
			methodMap.put(m.getName(), m);
		}
		String methodName = "get" + zdName.substring(0,1).toUpperCase()+zdName.substring(1);
		Object value = methodMap.get(methodName).invoke(vo);
		return value;
	}
	
	
	/**浮点型处理  保留2位小数点  通用报表
	 */
	public  String comFloat(String num){
		if("--".equals(num)){
			return "--";
		}
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(Double.parseDouble(num));
	}
	
	/**整数型  千分位处理    通用报表
	 */
	public String comInt(String num){
		if("--".equals(num)){
			return "--";
		}
		DecimalFormat df = new DecimalFormat("#,###.###");
		return df.format(Double.parseDouble(num));
	}
	
	
	/**整数型  千分位处理    通用报表  （无科学计数）
	 */
	public String comIntNOS(String num){
		if("--".equals(num)){
			return "--";
		}
		DecimalFormat df = new DecimalFormat("#######");
		return df.format(Double.parseDouble(num));
	}
	
	/**百分比转换  通用报表
	 */
	public  String comRate(String num){
		if("--".equals(num)){
			return "--";
		}
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(Double.parseDouble(num)*100)+"%";
	}
	
	
	/** 将百分比数值赋予颜色 （大于0则红色  小于0则蓝色  不变为黑色）
	 * @param num1  OO.XX%
	 * @return
	 */
	public String setColor(Object num){
		double value = Double.valueOf(num.toString().substring(0,num.toString().indexOf("%")));
		if(value == 0){
			return  "<font color=\"#000000\">0</font>";
		}
		if(value>0){
			return "<font color=\"#FF0000\">"+num+"</font>";
		}else if(value <0){
			return "<font color=\"#0000FF\">"+num+"</font>";
		}
		
		return "--";
	}
	
	
	/** 将百分比数值相减并根据值赋予颜色 （大于0则红色  小于0则蓝色  不变为黑色）
	 * @param num  OO.XX
	 * @return
	 */
	public String setColorSub(Object num1,Object num2){
		double value1 = Double.valueOf(num1.toString());
		double value2 = Double.valueOf(num2.toString());
		
		double subValue = value1  - value2;
		
		DecimalFormat df = new DecimalFormat("0.00");
		
		if(subValue == 0){
			return  "<font color=\"#000000\">0";
		}
		if(subValue>0){
			return "<font color=\"#FF0000\">"+df.format(subValue*100);
		}else if(subValue <0){
			return "<font color=\"#0000FF\">"+df.format(subValue*100);
		}
		
		return "--";
	}
	
	
	/**根据类型将值转换成不同数字格式
	 * @param value
	 * @param type   0 : 整型  1：浮点  2：百分比
	 * @return
	 */
	public String tranValueByType(Object value, int type){
		
		String result = "";
		switch (type) {
		case 0:
			result = qfw(value);
			break;
			
		case 1:
			result = xsd2(Double.parseDouble(value.toString()));
			break;
		case 2:
			result = tranRateTwo(Double.parseDouble(value.toString()));
			break;

		}
		return result;
	}
	
	/**检查数据权限
	 * @param bcList
	 * @param id
	 * @return
	 */
	public boolean  checkUserDP(Object dpValue,Object id){
		if(null != dpValue && !"".equals(dpValue)){
			if("0".equals(dpValue)){
				return true;
			}
			String a = String.valueOf(id);
			String[] fs =  dpValue.toString().split(",");
			for(String f : fs){
				if(f.equals(a))
					return true;
			}
		}
		return false;
	}
	
	 //计算占比 num1/num2
    public String compRateDirect(Object num1,Object num2){
    	if(num1==null||num2==null)
    		return "--";
		DecimalFormat df = new DecimalFormat("0.00");
		DecimalFormat df2 = new DecimalFormat("0.00000");
		
		double num_one = Double.valueOf(df2.format(num1));
		double num_two = Double.valueOf(df2.format(num2));
		
		if(num_two == 0){
			return  "0";
		}
		double sss = (num_one)/num_two;
		if(sss>0){
			return df.format(sss*100)+"%";
		}else{
			return "--";
		}
		
	}
	

    public double compDecimalRate(Object num1,Object num2){
    	if(num1==null && num2==null)
    		return 0;
    	else if(num1==null)
    		return -1;
    	else if(num2==null)
    		return 1;
		DecimalFormat df2 = new DecimalFormat("0.00000");
		
		double num_one = Double.valueOf(df2.format(num1));
		double num_two = Double.valueOf(df2.format(num2));
		if(num_one == 0 && num_two == 0)
			return 0;
		else if(num_one == 0){
			return -1;
		}
		else if(num_two == 0){
			return  1;
		}
		double sss = (num_one)/num_two;
		return sss;
		
    }
    
    public double compRate3(Object num1,Object num2){
		if(null != num1 && emptyStrSet.contains(num1.toString()))
			num1=null;
		if(null != num2 && emptyStrSet.contains(num2.toString()))
			num2=null;
		if(num1==null && num2==null)
    		return 0;
    	else if(num1==null)
    		return -1;
    	else if(num2==null)
    		return 1;
//		DecimalFormat df2 = new DecimalFormat("0.000000");
		
		String strVal1=String.valueOf(num1);
		String strVal2=String.valueOf(num2);
		
		double num_one = Double.valueOf(strVal1);
		double num_two = Double.valueOf(strVal2);
		if(num_one == 0 && num_two == 0)
			return 0;
		else if(num_one == 0){
			return -1;
		}
		else if(num_two == 0){
			return  1;
		}
		double sss = (num_one-num_two)/num_two;
		return sss;
	}
    
	 /**
     * 获取当前日期是星期几<br>
     * 
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(String date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date dt = DateUtil.strToDate(date, "yyyy-MM-dd");
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
}
